const baseUrlZk = import.meta.env.VITE_APP_ZK_API

export default {
    processZK: async (data, onChunkReceived, signal) => {
        const url = baseUrlZk + '/v1/base/process_zk'
        const response = await fetch(url, {
            method: 'POST',
            body: data,
            signal: signal 
        })
        // 检查响应是否成功
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        // 获取响应体的 readable stream
        const reader = response.body.getReader()
        const decoder = new TextDecoder('utf-8')
        

        try {
            while (true) {
              // 检查是否已取消请求
                if (signal && signal.aborted) {
                    throw new Error('Request aborted')
                }
                
                const { done, value } = await reader.read()
                if (done) break
                
                // 解码接收到的数据块
                const chunk = decoder.decode(value, { stream: true })
                
                // 调用回调函数处理数据块
                onChunkReceived(chunk)
                }
        } catch (error) {
            // 如果是中止错误，重新抛出
            if (signal && signal.aborted) {
                throw new DOMException('The user aborted a request.', 'AbortError')
            }
            throw error
        } finally {
            reader.releaseLock()
        }
    },
    str2docx: async (data) => { 
        const url = baseUrlZk + '/v1/base/str2docx'
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        
        // 检查响应是否成功
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        // 获取 Blob 格式的响应体（DOCX 文件）
        const blob = await response.blob()
        
        // 返回 Blob 对象，便于后续处理
        return blob
    }
}